<template>
<div class="queryProducts">
  <div>
    <div class="search">
      <Input v-model="value" placeholder="请输入你要查询的内容" style="width: 300px" clearable @on-enter="reGetproducts" />
      <Button type="primary" icon="ios-search" @click="queryGood">查询</Button>
      <Button type="warning" @click="flag = true">添加产品</Button>
    </div>
    <div class="productsInfo">
      <Table max-height="600px" border :columns="producsTitle" :data="products">
        <template slot-scope="{ row,index }" slot="action">
          <Button type="primary" size="small" style="margin-right: 10px" @click="sendDate(row)">修改</Button>
          <Button type="error" size="small" style="margin-right: 10px" @click="remove(index)">删除</Button>
          <Button type="primary" size="small" @click="adminProImg(index)">产品图片管理</Button>
        </template>
      </Table>
    </div>
  </div>

  <div>
    <Modal title="产品添加" v-model="flag" class-name="vertical-center-modal" draggable width="800" footer-hide>
      <div class="addProducts">
        <div class="menusItem">
          <span>产品类型:</span>
          <Input v-model="ptId" placeholder="请输入产品类型ID" clearable style="width: 200px" />

          <span class="rightItem">商品标题:</span>
          <Input v-model="pTitle" placeholder="请输入商品名称" clearable style="width: 200px" />
        </div>
        <div class="menusItem">
          <span>产品旧价:</span>
          <Input v-model="pPriceOld" placeholder="请输入产品之前价格" clearable style="width: 200px" />

          <span class="rightItem">产品现价:</span>
          <Input v-model="pPriceCur" placeholder="请输入产品当前价格" clearable style="width: 200px" />
        </div>
        <div class="menusItem">
          <span>库存数量:</span>
          <InputNumber :min="1" v-model="pStock" width="200" number></InputNumber>

          <span class="rightItem">添加日期:</span>
          <DatePicker type="date" placeholder="请选择日期" style="width: 200px"></DatePicker>
        </div>
        <div class="menusItem">
          <span>是否热卖:</span>
          <RadioGroup v-model="hot">
            <Radio label="✔" border></Radio>
            <Radio label="✖" border></Radio>
          </RadioGroup>
          <span style="height:10px;display:block;"></span>
          <span class="rightTui">是否推荐:</span>
          <RadioGroup v-model="tui">
            <Radio label="✔" border></Radio>
            <Radio label="✖" border></Radio>
          </RadioGroup>
        </div>
        <div class="menusItem">
          <span>产品图片:</span>
          <Input v-model="file" placeholder="产品上传的图片地址" clearable style="width: 200px" />
          <Upload   type="drag"
                    name="imgs"
                    :action="uploadUri"
                    :on-success="handleUploadSuccess"
                    :with-credentials="true"
                    :headers="headers"
                    :format="['jpg','jpeg','png','gif']">
            <div style="padding: 20px 0">
              <Icon type="ios-cloud-upload" size="52" style="color: #3399ff"></Icon>
              <p>请上传图片,推荐使用133x168比例的图片。</p>
            </div>
          </Upload>
        </div>
        <Button type="info" @click="addProduct">保存</Button>
      </div>
    </Modal>
  </div>

  <div>
    <Modal title="修改产品" v-model="modal10" class-name="vertical-center-modal" width="1220" draggable @on-ok="ok" @on-cancel="cancel">
      <Table max-height="600px" border :columns="rowsTitle" :data="rows">
        <template slot-scope="{ row }" slot="p_id">
          <span>{{ row.p_id }}</span>
        </template>
        <template slot-scope="{ row }" slot="pt_Id">
          <Input type="text" v-model="ptId" v-if="inputFlag" autofocus />
          <span v-else>{{ row.pt_Id }}</span>
        </template>
        <template slot-scope=" { row }" slot="p_title">
          <Input type="text" v-model="pTitle" v-if="inputFlag" clearable />
          <span v-else>{{ row.p_title }}</span>
        </template>
        <template slot-scope="{ row }" slot="p_price_old">
          <Input type="text" v-model="pPriceOld" v-if="inputFlag" clearable />
          <span v-else>{{ row.p_price_old }}</span>
        </template>
        <template slot-scope="{ row }" slot="p_price_cur">
          <Input type="text" v-model="pPriceCur" v-if="inputFlag" clearable />
          <span v-else>{{ row.p_price_cur }}</span>
        </template>
        <template slot-scope="{ row }" slot="p_stock">
          <InputNumber type="text" v-model="pStock" v-if="inputFlag"></InputNumber>
          <span v-else>{{ row.p_stock }}</span>
        </template>
        <template slot-scope="{ row }" slot="p_hot">
          <Input type="text" v-model="pHot" v-if="inputFlag" />
          <span v-else>{{ row.p_hot }}</span>
        </template>
        <template slot-scope="{ row }" slot="p_flag">
          <Input type="text" v-model="pFlag" v-if="inputFlag" />
          <span v-else>{{ row.p_flag }}</span>
        </template>
        <template slot-scope="{ row}" slot="action">
          <div v-if="inputFlag">
            <Button @click="UpdateProduct(row)">保存</Button>
          </div>
          <div v-else>
            <Button @click="showInput(row)">操作</Button>
          </div>
        </template>
      </Table>
    </Modal>
  </div>
</div>
</template>

<script>
import conf from '@/api/apiConf'
export default {
  data: () => ({

    uploadUri:conf.uploadFile, //后台上传图片地址
    headers:{'Access-Control-Allow-Origin':'*'},
    value: '',
    flag: false,
    modal10: false,
    inputFlag: false,
    modal3: false,
    file:null,
    rows: [],
    products: [],
    rowsTitle: [{
        title: 'ID',
        key: 'p_id',
        width: 70,
        align: 'center',
        slot: 'p_id',
      },
      {
        title: '类型',
        key: 'pt_Id',
        width: 70,
        align: 'center',
        slot: 'pt_Id',
      },
      {
        title: '商品标题',
        key: 'p_title',
        // width: 200,
        align: 'center',
        ellipsis: true,
        slot: 'p_title',
      },
      {
        title: '商品价格',
        key: 'p_price_old',
        width: 120,
        align: 'center',
        slot: 'p_price_old',
      },
      {
        title: '当前价格',
        key: 'p_price_cur',
        width: 120,
        align: 'center',
        slot: 'p_price_cur',
      },
      {
        title: '库存数量',
        key: 'p_stock',
        width: 100,
        align: 'center',
        slot: 'p_stock',
      },
      {
        title: '添加时日期',
        key: 'p_create',
        // width: 180,
        ellipsis: true,
        align: 'center',
      },
      {
        title: '是否热卖',
        key: 'p_hot',
        width: 100,
        align: 'center',
        slot: 'p_hot',
      },
      {
        title: '是否推荐',
        key: 'p_flag',
        width: 100,
        align: 'center',
        slot: 'p_flag',
      },
      {
        title: '操作',
        slot: 'action',
        width: 150,
        align: 'center',
      },
    ],
    producsTitle: [{
        title: 'ID',
        key: 'p_id',
        width: 70,
        align: 'center',
      },
      {
        title: '产品类型',
        key: 'pt_Id',
        width: 100,
        align: 'center',
      },
      {
        title: '商品标题',
        key: 'p_title',
        // width: 200,
        align: 'center',
        ellipsis: true,
      },
      {
        title: '商品价格(￥)',
        key: 'p_price_old',
        width: 120,
        align: 'center',
      },
      {
        title: '当前价格(￥)',
        key: 'p_price_cur',
        width: 120,
        align: 'center',
      },
      {
        title: '库存数量',
        key: 'p_stock',
        // width: 100,
        align: 'center',
      },
      {
        title: '添加时日期',
        key: 'p_create',
        width: 180,
        ellipsis: true,
        align: 'center',
      },
      {
        title: '是否热卖',
        key: 'p_hot',
        width: 100,
        align: 'center',
      },
      {
        title: '是否推荐',
        key: 'p_flag',
        width: 100,
        align: 'center',
      },
      {
        title: '操作',
        slot: 'action',
        width: 300,
        align: 'center',
      },
    ],
    hot: '✔',
    tui: '✔',
    ptId: '',
    pTitle: '',
    pPriceOld: '',
    pPriceCur: '',
    pStock: 0,
    pHot: '',
    pFlag: '',
  }),
  created() {
    this.GetProductHome()
  },
  methods: {
    adminProImg(index){
      let id=this.products[index].p_id
      this.$router.push({
          //  path: `/adminProImg?img_id=3`,
        // 使用下列方法方法跳转路由，就不会出现点击tab后再次跳转的bug
        name: 'adminProImg',
        params: { img_id: id }
       })
    },
    handleUploadSuccess(file){
      //获取当前网页的完整地址
     var url = window.location.href;
     var urlstr = url.split("/"); //以“/”进行分割
     var urls = '';
     if (urlstr[2]) {
         urls = urlstr[0]+'//'+urlstr[2];
     }
     if(urls.search(':')>0){
       urlstr=urls.split(":")
       urls=urlstr[0]+":"+urlstr[1]
     }
      this.file =urls+ file.data.path.replace('public','/mogu');
    },
    reGetproducts() {
      this.products = this.products.filter((el, index) => {
        return el.p_title.indexOf(this.value) != -1
      })
      if (this.value == '') this.GetProductHome()
    },
    queryGood() {
       this.GetProductHome(this.value)
    },
    async addProduct() {
      try {
        if (this.hot == '✔') {
          this.pHot = 1
        } else {
          this.pHot = 0
        }
        if (this.tui == '✔') {
          this.pFlag = 1
        } else {
          this.pFlag = 0
        }
        let params = {
          'productTypeId': this.ptId,
          'productTitle':this.pTitle,
          'productOddPrice': this.pPriceOld,
          'productNowProdut':this.pPriceCur,
          'productNum':this.pStock,
          'productHot':this.pHot,
          'productRecommend': this.pFlag,
          "proImg":this.file
        }
        if(this.inspectKey(params)) return
       let res= await this.$http.post(conf.addProduct, params)
       if(res.data.status==200){
         this.$Message.info('添加成功')
       }else{
         this.$Message.info('添加失败')
       }
        this.GetProductHome()
        this.flag = false
      } catch (error) {
        console.log(error)
      }
    },
    sendDate(row) {
      this.modal10 = true
      this.rows.push(row)
    },
    async UpdateProduct(row) {
      row.pt_Id = this.ptId
      row.p_title = this.pTitle
      row.p_price_old = this.pPriceOld
      row.p_price_cur = this.pPriceCur
      row.p_stock = this.pStock
      row.p_hot = this.pHot
      row.p_flag = this.pFlag
      let params = new URLSearchParams()
      params.append('id', row.p_id)
      params.append('productTypeId', row.pt_Id)
      params.append('productTitle', row.p_title)
      params.append('productOddPrice', row.p_price_old)
      params.append('productNowProdut', row.p_price_cur)
      params.append('productNum', row.p_stock)
      params.append('productHot', row.p_hot)
      params.append('productRecommend', row.p_flag)
      if(this.inspectKey(params)) return
      await this.$http.post(conf.UpdateProduct, params)
      this.GetProductHome()
      this.inputFlag = false
    },
    showInput(row) {
      this.ptId = row.pt_Id
      this.pTitle = row.p_title
      this.pPriceOld = row.p_price_old
      this.pPriceCur = row.p_price_cur
      this.pStock = row.p_stock
      this.pHot = row.p_hot
      this.pFlag = row.p_flag
      this.inputFlag = !this.inputFlag
    },
    ok() {
      this.modal10 = false
      this.rows = []
      this.inputFlag = false
    },
    cancel() {
      this.rows = []
      this.inputFlag = false
    },
    remove(index) {
      // this.modal3 = true
      this.products.splice(index, 1)
    },
    inspectKey(obj){
          let errKey='',flag=false
          for (const key in obj) {
              if (Object.hasOwnProperty.call(obj, key)) {
                  if(!obj[key]) {
                      flag=true
                      errKey=key
                  }
              }
          }
          this.$Message.info('不填字段不能为空')
          return flag
    },
    async GetProductHome(content='') {
      try {
        const {
          data: {
            data
          },
        } = await this.$http.get(conf.searchProductBuyContent+`?content=${content}`)
        this.products = data
        // console.log(this.products)
      } catch (error) {
        console.log('数据获取失败', error)
      }
    },
  },
}
</script>

<style lang="less" scoped>
.queryProducts {
  .search {
    margin: 20px;

    button {
      margin-left: 30px;
    }
  }

  .productsInfo {
    padding: 20px;
  }
}

.addProducts {
  padding: 20px 50px;

  .menusItem {
    margin-bottom: 20px;

    span,
    label {
      font-size: 17px;
      vertical-align: middle;
      margin-right: 10px;
      font-family: '宋体';
      font-weight: 600;
      margin-left: 30px;
    }

    .rightItem {
      margin-left: 50px;
    }

    .rightTui {
      margin-top: 10px;
    }

    #menu {
      width: 200px;
      height: 32px;
      line-height: 1.5;
      padding: 4px 7px;
      font-size: 14px;
      border: 1px solid #dcdee2;
      border-radius: 4px;
      color: #515a6e;
      background-color: #fff;
    }
  }

  .ivu-input-number {
    width: 200px;
  }

  .ivu-upload {
    width: 650px;
    margin-top: 10px;
  }

  button {
    margin-right: 50px;
    margin-top: 20px;
    width: 650px;
    height: 30px;
  }
}
</style>
